const puppeteer = require("puppeteer");

let convertHTMLToPDF = async (
	arg,
	callback,
	options = null,
	puppeteerArgs,
	remoteContent = false
) => {
	if (typeof arg.url !== "string") {
		throw new Error(
			"Invalid Argument: HTML expected as type of string and received a value of a different type. Check your request body and request headers."
		);
	}
	let browser;
	if (puppeteerArgs) {
		browser = await puppeteer.launch(puppeteerArgs);
	} else {
		browser = await puppeteer.launch({
			args: ["--no-sandbox", "--disable-setuid-sandbox"],
			executablePath: "/usr/bin/google-chrome",
		});
	}

	const page = await browser.newPage();

	if (!options) {
		options = {
			format: "Tabloid",
			printBackground: true,
			"-webkit-print-color-adjust": "exact",
		};
	}
	if (remoteContent === true) {
		await page.goto(arg.url, {
			timeout: 0,
			waitUntil: "networkidle0",
		});
	} else {
		//page.setContent will be faster than page.goto if html is a static
		await page.goto(arg.url, {
			timeout: 0,
			waitUntil: "networkidle0",
		});
	}
	//await page.content();
	//await page.waitForNetworkIdle({ concurrency: 0, idleTime: 1000 });
	await page.pdf(options).then(callback, function (error) {
		console.log(error);
	});
	await browser.close();
};

module.exports = convertHTMLToPDF;
